<?php

namespace app\channel\model;
use app\BaseModel;
use think\facade\Cache;
use think\Db;
use app\channel\model\ProxyUpapplyLogModel;
//*------------------------------------------------------ */
//-- 代理层级
/*------------------------------------------------------ */

class ProxyLevelModel extends BaseModel
{
    protected $table = 'channel_proxy_level';
    public $pk = 'proxy_id';
    protected $mkey = 'channel_proxy_level_mkey_';

    /*------------------------------------------------------ */
    //-- 清除活动商品缓存
    /*------------------------------------------------------ */
    public function cleanMemcache(){
        Cache::rm($this->mkey . 'list');
    }
    /*------------------------------------------------------ */
    //-- 代理层级列表
    //-- $addFactory bool 是否增加厂家
    /*------------------------------------------------------ */
    public function getList($addFactory = false){
        Cache::rm($this->mkey . 'list');
        $list = Cache::get($this->mkey . 'list');
        if (empty($list) == true){
            $rows = $this->order('level ASC')->select()->toArray();
            if (empty($rows)){
               return [];
            }
            $list = [];
            foreach ($rows as $row){
                if ($row['pid'] == 0){
                    $row['pid_name'] = '厂家';
                }else{
                    $row['pid_name'] = $list[$row['pid']]['proxy_name'];
                }
                if ($row['supply_pid'] == 0){
                    $row['supply_name'] = '厂家';
                }else{
                    $row['supply_name'] = $list[$row['supply_pid']]['proxy_name'];
                }
                $row['upgrade_limit_proxy_arr'] = explode(',',$row['upgrade_limit_proxy']);
                $list[$row['proxy_id']] = $row;

            }
            Cache::set($this->mkey . 'list', $list, 600);
        }
        if ($addFactory == true){
            array_unshift($list,['proxy_id'=>0,'proxy_name'=>'厂家','pid'=>-1]);
        } else {
            $end = end($list);
            $list[0] = [
                'proxy_id' => 0,
                'proxy_name' => '无身份',
                'pid' => $end['proxy_id'],
                'supply_pid' => $rows[count($rows) - 2]['proxy_id'],
                'level' => 99,
                'upgrade_limit_proxy_arr' => '',
            ];
        }
        return $list;
    }

    /*------------------------------------------------------ */
    //-- 代理层级信息
    /*------------------------------------------------------ */
    public function info($proxy_id,$returnName=false){
        $list = $this->getList();
        if ($returnName == true){
            return $list[$proxy_id]['proxy_name'];
        }
        return $list[$proxy_id];
    }
    /*------------------------------------------------------ */
    //-- 代理汇总
    /*------------------------------------------------------ */
    public function proxyStatc(){
        $statc = Cache::get($this->mkey . 'statc');
        if (empty($statc) == true){
            $where[] = ['status','>',0];
            $statc = (new ProxyUsersModel)->where($where)->group('proxy_id')->column('count(user_id) as count','proxy_id');
            Cache::set($this->mkey . 'statc', $statc, 30);
        }
        $data['allNum'] = 0;
        foreach ($statc as $val){
            $data['allNum'] += $val;
        }
        $list = $this->getList();
        foreach ($list as $row){
            $num = 0;
            if (empty($statc[$row['proxy_id']]) == false){
                $num = $statc[$row['proxy_id']];
            }
            $data['statc'][$row['proxy_id']]['num'] = $num;
            $data['statc'][$row['proxy_id']]['pre'] = priceFormat($num / $data['allNum'] * 100);
        }
        return $data;
    }
    /*------------------------------------------------------ */
    //-- 更新层级排序
    /*------------------------------------------------------ */
    public function upLevel($pid = 0,$level = 1){
        $proxy_id = $this->where('pid',$pid)->value('proxy_id');
        if ($proxy_id < 1) return true;
        $this->where('pid',$pid)->update(['level'=>$level]);
        return $this->upLevel($proxy_id,$level+1);
    }
    /*------------------------------------------------------ */
    //-- 获取可邀请层级
    //-- $proxy_id intval 邀请人层级
    //-- $invite_proxy_id int 邀请的层级
    /*------------------------------------------------------ */
    public function getInvitelist($proxy_id,$invite_proxy_id = 0){
        $rows = $this->getList();
        $proxy = $rows[$proxy_id];
        $list = [];
        foreach ($rows as $key=>$row) {
            if ($invite_proxy_id > 0 && $invite_proxy_id != $row['proxy_id']){
                continue;
            }
            if ($proxy_id > 0){
                if ($row['is_invite'] == 0){
                    continue;
                }
                if ($proxy['invite_setting'] == 2 && $row['level'] < $proxy['level']){
                    continue;
                }
                if($proxy['invite_setting'] == 3 && $row['level'] <=  $proxy['level']){
                    continue;
                }
            }
            $data['value'] = $row['proxy_id'];
            $data['label'] = $row['proxy_name'];
            $data['limit_tip'] = '';
            $limit = [];
            if ($row['is_join_limit'] == 1){
                if ($row['join_uplevel_goods_money_limit'] == 1){
                    $limit[] = '充值升级货款:￥'.$row['uplevel_goods_money'];
                }
                if ($row['join_goods_money_limit'] == 1){
                    $limit[] = '充值货款:￥'.$row['join_goods_money'];
                }
                if ($row['join_earnest_money_limit'] == 1){
                    $limit[] = '充值保证金:￥'.$row['join_earnest_money'];
                }
                if ($row['order_first_cloud_limit'] == 1){
                    $limit[] = '完成首笔云仓订单:￥'.$row['order_first_cloud_money'];
                }
                if ($row['order_first_spot_limit'] == 1){
                    $limit[] = '完成首笔现货订单:￥'.$row['order_patch_spot_money'];
                }
                $data['limit_tip'] = join('，',$limit);
            }
            $list[] = $data;
        }
        return $list;
    }
    /*------------------------------------------------------ */
    //-- 获取可升级层级
    //-- $user_id intval 会员ID
    //-- $proxy_id intval 会员代理层级
    /*------------------------------------------------------ */
    public function getUpgradeLevel($user_id,$proxy_id){
        $levelList = $this->getList();
        $proxy = $levelList[$proxy_id];//当前层级
        if($proxy_id <= 0){
            $proxy['level'] = 99;
        }
        $rows = array_reverse($levelList);//反转数组
        $data['upList'] = [];
        $data['appliedList'] = [];
        $data['stepsNum'] = 0;//跳过低级代理数
        $account = (new WalletModel)->where('user_id',$user_id)->find();
        // $ProxyUsersModel = new ProxyUsersModel();
        // $pushNum = $ProxyUsersModel->where('pid',$user_id)->count();//直推人数
        // $ProxyUsersSuperiorModel = new ProxyUsersSuperiorModel();
        $where[] = ['','exp',Db::raw("FIND_IN_SET('".$user_id."',superior)")];
        // $teamNum = $ProxyUsersSuperiorModel->where($where)->count();//团队人数，含平级，更高级
         $RechargeLogModel = new RechargeLogModel();
        // 当前补货
        $ChannelOrderModel = new OrderModel();
        $new_order = $ChannelOrderModel->getAllAmount($this->userInfo['user_id']);
        $proxyUpapplyLogModel = new ProxyUpapplyLogModel();
        foreach ($rows as $key=>$row) {
            /*if ($row['upgrade_type'] == 0){//手动调整的跳过
                continue;
            }*/
            $info = $proxyUpapplyLogModel->where(['status'=>1,'up_proxy_id'=>$row['level'],'user_id'=>$this->userInfo['user_id']])->find();
            if ($row['level'] >= $proxy['level']){
                $data['stepsNum']++;
                $data['appliedList'][] = $row;
            }else{
                if(!$info) {
                    $data['stepsNum']++;
                }
                $isup = true;
                if (empty($row['upgrade_limit_proxy']) == false){//没有设置即不限制
                    $upgrade_limit_proxy = explode(',',$row['upgrade_limit_proxy']);
                    if (in_array($proxy_id,$upgrade_limit_proxy) == false){
                        $isup = false;
                    }
                }
                if ($isup == true){
                    $_row = [];
                    $_row['proxy_id'] = $row['proxy_id'];
                    $_row['proxy_name'] = $row['proxy_name'];
                    $_row['label'] = $row['proxy_name'];
                    $_row['value'] = $row['proxy_id'];
                    $_row['upgrade_all_limit'] = $row['upgrade_all_limit'];

                    /*if ($row['upgrade_uplevel_goods_money_limit'] == 1){
                        $condition = '充值升级货款:￥'.$row['uplevel_goods_money'];
                        $_row['diff_uplevel_goods_money'] = $row['uplevel_goods_money'] - $proxy['uplevel_goods_money'];//计算出差价
                        $_row['uplevel_goods_money_status'] = 0;
                        if ($_row['diff_uplevel_goods_money'] > 0) {
                            $condition .= '，需支付(￥'.$_row['diff_uplevel_goods_money'].')';
                            $where = [];
                            $where[] = ['user_id','=',$user_id];
                            $where[] = ['type','=','uplevelGoodsMoney'];
                            $where[] = ['order_amount','=',$_row['diff_uplevel_goods_money']];
                            $rechargeLog = $RechargeLogModel->where($where)->order('order_id DESC')->find();
                            if (empty($rechargeLog) == false){
                                if ($rechargeLog['status'] == 0){
                                    $condition .= '，已提交充值，待审核.';
                                }elseif ($rechargeLog['status'] == 1){
                                    $condition .= '，提交的充值被拒绝，如有问题请联系平台.';
                                }else{
                                    $_row['uplevel_goods_money_status'] = 9;
                                    $condition .= '，已满足条件.';
                                }
                            }

                        }
                        $_row['condition'][] = ['text'=>$condition,'status'=>$_row['uplevel_goods_money_status']];
                    }

                    if ($row['upgrade_earnest_money_limit'] == 1){
                        $_row['upgrade_earnest_money_status'] = 0;
                        $condition = '保证金:￥'.$row['upgrade_earnest_money'];
                        $_row['diff_earnest_money'] = $row['upgrade_earnest_money'] - $account['earnest_money'];
                        if ($_row['diff_earnest_money'] > 0){
                            $condition .='，当前保证金:￥'.$account['earnest_money'].',需支付(￥'.$_row['diff_earnest_money'].')';
                        }else{
                            $_row['upgrade_earnest_money_status'] = 9;
                            $condition .='，已满足条件.';
                        }
                        $_row['condition'][] = ['text'=>$condition,'status'=>$_row['upgrade_earnest_money_status']];
                    }
                    if ($row['upgrade_team_limit'] == 1){
                        $_row['upgrade_team_status'] = 9;
                        $condition = '团队要求';
                        if ($row['upgrade_direct_push_num'] > 0){
                            $condition .= '，要求直推:'.$row['upgrade_direct_push_num'].'人，当前人数:'.$pushNum.'人';
                        }
                        if ($row['upgrade_team_proxy_id'] > 0 && $row['upgrade_team_proxy_num'] > 0){
                            $condition .= '，直推【'.$levelList[$row['upgrade_team_proxy_id']]['proxy_name'].'】:'.$row['upgrade_team_proxy_num'].'人';
                            $where = [];
                            $where[] = ['pid','=',$user_id];
                            $where[] = ['proxy_id','=',$row['upgrade_team_proxy_id']];
                            $proxyNum = $ProxyUsersModel->where($where)->count();
                            $condition .= '，当前人数:'.$proxyNum.'人';
                            if ($row['upgrade_team_proxy_num'] > $proxyNum){
                                $_row['upgrade_team_status'] = 0;
                            }
                        }
                        if ($row['upgrade_team_all_num'] > 0){
                            $condition .= '，要求团队总人数:'.$row['upgrade_team_all_num'].'人';
                            $condition .= '，当前人数:'.$teamNum.'人';
                            if ($_row['upgrade_team_status'] > $teamNum){
                                $_row['upgrade_team_status'] = 0;
                            }
                        }
                        if ($_row['upgrade_team_status'] == 9){
                            $condition .='，已满足条件.';
                        }
                        $_row['condition'][] = ['text'=>$condition,'status'=>$_row['upgrade_team_status']];
                    }*/
                    // 进货
                    if($row['replenish_money'] > 0){
                        $_row['replenish_money_status'] = 4;
                        $_row['earnest_money_status'] = 0;
                        $condition = '补货要求';
                        // 当前补货
                        if ($row['replenish_money'] > 0){
                            $condition .= '，要求累计补货:'.$row['replenish_money'].'元，当前:'.$new_order.'元';
                        }
                        if($row['replenish_money'] <= $new_order){
                            $condition .='，已满足条件.';
                            $_row['replenish_money_status'] = 5;
                        } else {
                            $_row['replenish_money_status'] = 0;
                        }
                        $_row['condition'][] = ['text'=>$condition,'status'=>$_row['replenish_money_status']];
                    }
                    if($row['earnest_money'] > 0){
                        $_row['earnest_money_status'] = 4;
                        $condition = '保证金要求';
                        // 当前保证金
                        if ($row['earnest_money'] > 0){
                            $condition .= '，要求累计充值保证金:'.$row['earnest_money'].'元，当前:'.$account['earnest_money_total'].'元';
                        }
                        if($row['replenish_money'] <= $account['earnest_money_total']){
                            $condition .='，已满足条件.';
                        } else {
                            $condition .=',需支付(￥'.($row['earnest_money'] - $account['earnest_money_total']).')';
                            if ($_row['replenish_money_status']!=5) {
                                $_row['replenish_money_status'] = 9;
                            }
                        }
                        $_row['diff_earnest_money'] = $row['earnest_money'] - $account['earnest_money_total'];
                        if ($_row['replenish_money_status']!=5) {
                            $_row['condition'][] = ['text' => $condition, 'status' => $_row['earnest_money_status']];
                        }
                    }
                    if ($RechargeLogModel->where(['user_id'=>$this->userInfo['user_id'],'status'=>0])->find()) {
//                        $_row['replenish_money_status'] = 6;
                    }
                    $_row['replenish_money'] = $row['replenish_money'];
                    $data['upList'][] = $_row;
                }
                $data['stepsList'][] = ['name'=>$row['proxy_name']];
            }
        }
        $data['stepsNum'] -= 1;
        $data['applyLog'] = $this->getUserApplyLog($user_id);
        return $data;
    }
    /*------------------------------------------------------ */
    //-- 是否满升条件
    //-- $user_id intval 会员ID
    //-- $proxy_id intval 申请升级的层级
    /*------------------------------------------------------ */
    public function checkUpgrade($user_id,$proxy_id)
    {
        $levelList = (new ProxyLevelModel)->getList();
        if (empty($levelList[$proxy_id])) {
            return '没有找到对应升级的层级.';
        }
        $upLevel = $levelList[$proxy_id];
        $ProxyUsersModel = new ProxyUsersModel();
        $userInfo = $ProxyUsersModel->info($this->userInfo['user_id']);
        if ($upLevel['level'] > $userInfo['proxyLevel']['level'] && $userInfo['proxy_id'] > 0) {
            return '发生错误，你当前层级高于你选择升级的层级.';
        }
        $ProxyUsersSuperiorModel = new ProxyUsersSuperiorModel();
        $errorArr = [];
        if ($upLevel['upgrade_uplevel_goods_money_limit'] == 1) {
            $diff_uplevel_goods_money = $upLevel['uplevel_goods_money'] - $userInfo['proxyLevel']['uplevel_goods_money'];
            $isOk = true;
            if ($diff_uplevel_goods_money > 0) {
                $RechargeLogModel = new RechargeLogModel();
                $where = [];
                $where[] = ['user_id','=',$user_id];
                $where[] = ['type','=','uplevelGoodsMoney'];
                $where[] = ['order_amount','=',$diff_uplevel_goods_money];
                $rechargeLog = $RechargeLogModel->where($where)->order('order_id DESC')->find();
                if (empty($rechargeLog) == false){
                    if ($rechargeLog['status'] == 0){
                        $isOk = false;
                        $errorArr[] = '已提交充值，正在等待审核.';
                    }elseif ($rechargeLog['status'] == 1){
                        $isOk = false;
                        $errorArr[] = '提交的充值被拒绝，如有问题请联系平台.';
                    }
                }else{
                    $isOk = false;
                    $errorArr[] = '未满足升级条件，升级货款还需要充值：￥' . $diff_uplevel_goods_money;
                }
            }
            if ($isOk == true && $upLevel['upgrade_all_limit'] == 0){
                return true;
            }
        }
        if ($upLevel['upgrade_earnest_money_limit'] == 1) {
            $isOk = true;
            $diff_earnest_money = $upLevel['upgrade_earnest_money'] - $userInfo['account']['earnest_money'];
            if ($diff_earnest_money > 0) {
                $isOk = false;
                $errorArr[] = '未满足升级条件，保证金还需要充值：￥' . $diff_earnest_money;
            }
            if ($isOk == true && $upLevel['upgrade_all_limit'] == 0){
                return true;
            }
        }
        if ($upLevel['upgrade_team_limit'] == 1) {
            $isOk = true;
            $pushNum = $ProxyUsersModel->where('pid', $user_id)->count();
            if ($upLevel['upgrade_direct_push_num'] > 0 && $upLevel['upgrade_direct_push_num'] > $pushNum) {
                $isOk = false;
                $errorArr[] = '未满足升级条件，要求直推:' . $upLevel['upgrade_direct_push_num'] . '人，当前人数:' . $pushNum . '人';
            }
            if ($upLevel['upgrade_team_proxy_id'] > 0 && $upLevel['upgrade_team_proxy_num'] > 0) {
                $where = [];
                $where[] = ['pid', '=', $user_id];
                $where[] = ['proxy_id', '=', $upLevel['upgrade_team_proxy_id']];
                $proxyNum = $ProxyUsersModel->where($where)->count();
                if ($upLevel['upgrade_team_proxy_num'] > $proxyNum && $upLevel['upgrade_all_limit'] == 1) {
                    $isOk = false;
                    $errorArr[] = '未满足升级条件，直推【' . $levelList[$upLevel['upgrade_team_proxy_id']]['proxy_name'] . '】:' . $upLevel['upgrade_direct_push_num'] . '人，当前人数:' . $proxyNum . '人';
                }
                if ($upLevel['upgrade_team_all_num'] > 0) {
                    $where = [];
                    $where[] = ['', 'exp', Db::raw("FIND_IN_SET('" . $user_id . "',superior)")];
                    $teamNum = $ProxyUsersSuperiorModel->where($where)->count();
                    if ($upLevel['upgrade_team_all_num'] > $teamNum && $upLevel['upgrade_all_limit'] == 1) {
                        $isOk = false;
                        $errorArr[] = '未满足升级条件，要求团队总人数:' . $upLevel['upgrade_team_all_num'] . '人，当前人数:' . $teamNum . '人';
                    }
                }
            }
            if ($isOk == true && $upLevel['upgrade_all_limit'] == 0){
                return true;
            }
        }
        if (empty($errorArr) == false){
            return reset($errorArr);
        }
        return true;
    }

    /**
     * 用户已申请代理记录(未查看的记录)
     * @param $user_id
     */
    public function getUserApplyLog($user_id){
        $rechargeLog = new RechargeLogModel();

        $logs = $rechargeLog->where('user_id', $user_id)
            ->where('order_type', 1)
            ->where('user_check', 0)
            ->select();

        return $logs;
    }

}
